#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>


#include "icar.h"
#include "icar_sock.h"
#include "icar_log.h"
#include "icar_utils.h"


fdsets_t *firstfdsets = NULL;


void
icar_init_fdset(void)
{
	firstfdsets = NULL;
}

fdsets_t *
icar_get_first_fdset(void)
{
	return firstfdsets;
}

fdsets_t *
icar_new_fdset(void)
{
	fdsets_t *new = NULL;
	int i = 0;

	new = (fdsets_t *)icar_malloc(sizeof(fdsets_t));

	new->index = 0;
	for (i = 0; i < ARRAY_SIZE(new->fdsets); i++)
		new->fdsets[i] = -1;

	FD_ZERO(&new->rset);
	FD_ZERO(&new->allset);

	return new;
}

fdsets_t *
icar_fdset_list_append(fdsets_t *fd)
{
	fdsets_t *tmp;
	if (fd) {
		if (firstfdsets == NULL)
			firstfdsets = fd;
		else {
			for (tmp = firstfdsets; tmp->next != NULL; tmp = tmp->next);
			tmp->next = fd;
			fd->next = NULL;
		}
	}

	return fd;
}

fdsets_t *
icar_fdset_list_find(fdsets_t *fd)
{
	fdsets_t *tmp;
	if (firstfdsets == NULL || fd == NULL)
		return NULL;

	for (tmp = firstfdsets; tmp; tmp = tmp->next) {
		if (fd == tmp) {
			return fd;
		}
	}
	return NULL;
}

void
icar_fdset_list_delete(fdsets_t *fd)
{
	fdsets_t *tmp;

	if (firstfdsets == NULL)
		icar_daemon(LOG_ERR, "Node list empty!");
	else if (fd == firstfdsets)
	{
		firstfdsets = firstfdsets->next;
		free(fd);
		fd = NULL;
		icar_daemon(LOG_DEBUG, "Node is first node, and is deleted");
	} else {
		tmp = firstfdsets;
		while (tmp->next != NULL && tmp->next != fd)
			tmp = tmp->next;

		if (tmp->next == NULL) {
			icar_daemon(LOG_ERR, "Node to delete could not be found");
		} else {
			tmp->next = fd->next;
			free(fd);
			fd = NULL;
			icar_daemon(LOG_DEBUG, "Node is deleted");
		}
	}
}
